<template>
  <div>
    <div class="topcontainer">
      <h4>已关联表</h4>
    </div>
    <el-table
      type="border-card"
      :data="tableFieldLst"
      :row-style="{height:'30px'}"
      :cell-style="{padding:'0px'}"
      style="width: 100%;font-size: 10px"
      class="table"
      height="calc(100vh - 270px)"
    >
      <el-table-column prop="mainFieldName" label="主表字段名称" align="center">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.isDefault">
              {{
              scope.row.mainFieldName
              }}
            </span>
            <el-select v-else placeholder v-model="scope.row.mainFieldId">
              <el-option
                v-for="item in mainFieldLis"
                :key="item.fieldId"
                :label="item.fieldName"
                :value="item.fieldId"
              >{{ item.fieldName }}</el-option>
            </el-select>
            <!-- searchList -->
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="foreignTableName" label="副表名称" align="center">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.isDefault">
              {{
              scope.row.foreignTableName
              }}
            </span>
            <el-select
              v-else
              placeholder
              v-model="scope.row.foreignTableId"
              @change="changeforeignTableId"
            >
              <el-option
                v-for="item in searchList"
                :key="item.tableId"
                :label="item.tableName"
                :value="item.tableId"
              >{{ item.tableName }}</el-option>
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="foreignFieldName" label="副表字段名称" align="center">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.isDefault">
              {{
              scope.row.foreignFieldName
              }}
            </span>
            <el-select
              v-else
              placeholder
              v-model="scope.row.foreignFieldId"
              :disabled="!scope.row.foreignTableId"
            >
              <el-option
                v-for="item in foreignFieldList"
                :key="item.fieldId"
                :label="item.fieldName"
                :value="item.fieldId"
              >{{ item.fieldName }}</el-option>
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="foreignFieldName" label="操作" align="center">
        <template slot-scope="scope">
          <el-button @click="delTable(scope)" type="text" v-if="scope.row.isDefault">删除</el-button>
          <el-button @click="cancleJoin" type="text" v-else>取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="btn">
      <el-button type="primary" @click="addJoin" size="mini">添加关联</el-button>
      <el-button type="primary" @click="submitJoin" v-if="isAdd" size="mini">确定</el-button>
      <!-- <el-button type="primary" @click="cancleJoin" v-if="isAdd" size="mini"
        >取消</el-button
      >-->
    </div>
  </div>
</template>
<script>
import { api } from "../server/api";
export default {
  data() {
    return {
      tableId: "",
      tableFieldLst: [],
      searchList: [],
      mainFieldLis: [],
      foreignFieldList: [],
      pList: { mainFieldId: "", foreignTableId: "", foreignFieldId: "" },
      isAdd: false
    };
  },
  created() {
    console.log(this.tableId);
    this.tableId = this.$route.query.tableId;
    this.getDatils();
    this.getsearchList();
    this.getMainFieldList();
  },
  methods: {
    //获取显示的table列表
    getDatils() {
      api.stdappTableJoinLst(this.tableId).then(res => {
        res.map(item => {
          item.isDefault = true;
        });
        this.tableFieldLst = res;
      });
    },
    //获取除了当前表其他表的list
    getsearchList() {
      api.stdappTbls4Join().then(res => {
        this.searchList = res.filter(item => {
          return item.tableId != this.tableId;
        });
      });
    },
    //新增关联
    addJoin() {
      this.tableFieldLst.push({ isDefault: false });
      this.isAdd = true;
    },
    getMainFieldList() {
      api.stdappTableDetail({ tableId: this.tableId }).then(res => {
        let { fieldLst } = res;
        let arr = fieldLst.filter(item => {
          return (
            item.fieldType == "InputNumber" ||
            item.fieldType == "InputText" ||
            item.fieldType == "IdentityKey"
          );
        });
        console.log(arr);
        this.mainFieldLis = arr;
      });
    },
    changeforeignTableId(e) {
      console.log(e);
      this.foreignFieldList = [];
      this.getForeignFieldList(e);
    },
    getForeignFieldList(e) {
      api.stdappTableDetail({ tableId: e }).then(res => {
        console.log(res);
        let { fieldLst } = res;
        let arr = fieldLst.filter(item => {
          return (
            item.fieldType == "InputNumber" ||
            item.fieldType == "InputText" ||
            item.fieldType == "IdentityKey"
          );
        });
        console.log(arr);
        this.foreignFieldList = arr;
      });
    },
    submitJoin() {
      for (let index = 0; index < this.tableFieldLst.length; index++) {
        const element = this.tableFieldLst[index];
        const { mainFieldId, foreignTableId, foreignFieldId } = element;
        if (!mainFieldId || !foreignTableId || !foreignFieldId) {
          this.$message.warning("请选择");
          return;
        }
      }
      this.submit();
    },
    cancleJoin() {
      this.tableFieldLst.pop();
      if (this.tableFieldLst.length == 0) {
        this.isAdd = false;
      }
    },
    delTable(scope) {
      console.log(scope.$index);
      this.tableFieldLst.splice(scope.$index, 1);
      this.submit();
    },
    submit() {
      let arr = [];
      for (let index = 0; index < this.tableFieldLst.length; index++) {
        const element = this.tableFieldLst[index];
        const { mainFieldId, foreignTableId, foreignFieldId } = element;
        const obj = { mainFieldId, foreignTableId, foreignFieldId };
        if (mainFieldId && foreignTableId && foreignFieldId) {
          arr.push(obj);
        }
      }
      console.log(arr);
      const data = {
        tableId: this.tableId,
        pairLst: arr
      };
      console.log(data);
      api.stdappTableSetJoin(data).then(res => {
        console.log(res);
        this.dialogVisible = false;
        this.joinTableData = [];
        this.multipleSelection = [];
        this.allSelect = {};
        this.allData = [];
      });
      setTimeout(() => {
        this.tableFieldLst = [];
        this.isAdd = false;
        this.pList = {};
        this.$message.success("成功");
        this.getDatils();
      }, 1000);
    }
    // getjoinList() {
    //   api.stdappTableJoinLst(this.tableId).then(res => {
    //     console.log(res);
    //     let allSelect = {};
    //     for (let index = 0; index < res.length; index++) {
    //       const element = res[index];
    //       // this.mainFieldId
    //       if (element.mainFieldId == this.mainFieldId) {
    //         const key = element.foreignTableId;
    //         let obj = {
    //           fieldId: element.foreignFieldId,
    //           fieldName: element.foreignFieldName
    //         };
    //         allSelect[key] = allSelect[key] ? [...allSelect[key], obj] : [obj];
    //       } else {
    //         const { mainFieldId, foreignTableId, foreignFieldId } = element;
    //         this.allData.push({ mainFieldId, foreignTableId, foreignFieldId });
    //       }
    //     }
    //     this.allSelect = allSelect;
    //   });
    // },

    // handleSelectionChange(row) {
    //   const { tableId } = this.queryParams;
    //   console.log(tableId);
    //   this.multipleSelection = row;
    //   this.$nextTick(() => {
    //     this.$set(this.allSelect, tableId, row);
    //   });
    // },
    // removeRepeat(arr) {
    //   let newArr = [];
    //   let obj = {};
    //   newArr = arr.reduce((prev, cur) => {
    //     obj[cur.fieldId] ? "" : (obj[cur.fieldId] = true && prev.push(cur));
    //     return prev;
    //   }, []);
    //   return newArr;
    // },
    // resetQuery() {
    //   this.queryParams = {
    //     tableId: ""
    //   };
    // },
    // joinViceTable(row) {
    //   this.mainFieldId = row.fieldId;
    //   this.dialogVisible = true;
    //   this.$set(this.queryParams, "tableId", this.searchList[0].tableId);
    //   this.getFieldList();
    //   this.getjoinList();
    // },
    // getFieldList() {
    //   api.stdappTableDetail(this.queryParams).then(res => {
    //     let { fieldLst } = res;
    //     this.tableData = fieldLst;
    //     let data = this.allSelect[this.queryParams.tableId];
    //     setTimeout(() => {
    //       if (data) {
    //         for (let index = 0; index < data.length; index++) {
    //           const element = data[index];
    //           const val = fieldLst.find(item => {
    //             return item.fieldId === element.fieldId;
    //           });
    //           this.$refs.multipleTable.toggleRowSelection(val, true);
    //         }
    //       } else {
    //         this.$refs.multipleTable.clearSelection();
    //       }
    //     }, 100);
    //   });
    // },
    // submitJoin() {
    //   const arr = [];
    //   //  {"mainFieldId":45, "foreignTableId":8, "foreignFieldId":46},
    //   for (let key in this.allSelect) {
    //     console.log(this.allSelect[key]);
    //     const fieldLst = this.allSelect[key];
    //     for (let index = 0; index < fieldLst.length; index++) {
    //       const element = fieldLst[index];
    //       const obj = {
    //         mainFieldId: this.mainFieldId,
    //         foreignTableId: key,
    //         foreignFieldId: element.fieldId
    //       };
    //       arr.push(obj);
    //     }
    //   }
    //   // console.log([...arr, ...this.allData]);
    //   const data = {
    //     tableId: this.tableId,
    //     pairLst: arr
    //   };
    //   api.stdappTableSetJoin(data).then(res => {
    //     console.log(res);
    //     this.$message.success("关联成功");
    //     this.dialogVisible = false;
    //     this.joinTableData = [];
    //     this.multipleSelection = [];
    //     this.allSelect = {};
    //     this.allData = [];
    //   });
    // }
  }
};
</script>
<style lang="scss" scoped>
.topcontainer {
  display: flex;
  height: 60px;
  align-items: center;
  h4 {
    margin: 0 10px;
  }
}
.list {
  .title {
    display: inline-block;
    padding: 5px 0;
  }
  .el-tag {
    margin: 5px;
  }
}
.btn {
  display: flex;
  width: 100vw;
  align-items: center;
  justify-content: center;
  height: 50px;
  .el-button {
    height: 32px;
  }
}
</style>